<template>
  <el-dialog :title="dialogTitle" :visible="dialogVisible" @close="dialogClose">
    <el-form :model="stuForm" :rules="stuRules" ref="addTableInfo">
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action="http://chst.vip/students/uploadStuAvatar"
          :show-file-list="true"
          :on-success="uploadAvatarSuccess"
          :on-remove='removeAvatar'
          :before-upload="beforeAvatarUpload"
          :limit="limit"
          name="headimgurl"
          list-type="picture-card"
          :multiple="false"
          :file-list='headimgList'
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="stuForm.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="项目地址" prop="productUrl">
        <el-input v-model="stuForm.productUrl" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="班级" prop="class">
        <el-input v-model="stuForm.class" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="stuForm.age" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input v-model="stuForm.city" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="学历" prop="degree">
        <el-input v-model="stuForm.degree" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="stuForm.description" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="HIDE_DIALOG">取 消</el-button>
      <el-button type="primary" @click="commitStuInfo('addTableInfo')"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
// 将vuex中的数据放到这里
import { mapMutations, mapState, mapActions } from "vuex";
import * as api from "../../api";
export default {
  computed: {
    ...mapState(["dialogTitle", "dialogVisible",'currentRow']),
  },
  data() {
    return {
      limit:1,//用于控制上传头像的数量
      headimgList:[],//用于存储用户的头像，目的是实现头像的回显
      imageUrl: "",
      //   dialogTitle: "增加学员信息",
      //   dialogVisible: true, //控制dialog的显示隐藏
      stuForm: {
        //stufrom中的参数是和我们添加学员信息api中的参数对应的
        name: "",
        age: "",
        productUrl: "",
        description: "",
        class: "",
        city: "",
        degree: "",
        headimgurl: "",
      },
      oldForm:{},//用于存储stuFrom的初始值
      stuRules: {
        name: [{ required: true, message: "请输入名字", trigger: "blur" }],
        productUrl: [
          { required: true, message: "请输入项目地址", trigger: "blur" },
        ],
        class: [{ required: true, message: "请输入班级", trigger: "blur" }],
        age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
        city: [{ required: true, message: "请输入城市名", trigger: "blur" }],
        degree: [
          { required: true, message: "请输入你的学历", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入描述信息", trigger: "blur" },
        ],
      },
    };
  },
  created () {
    this.oldForm = {...this.stuForm}//存储stuFrom的初始值
  },

  methods: {
    ...mapActions(["GET_STU_INFO"]),
    ...mapMutations([
      "SHOW_DIALOG",
      "HIDE_DIALOG",
      "CHANGE_DIALOG_TITLE",
      "HIDE_LOADING",
    ]),
    //头像上传的逻辑
    uploadAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    removeAvatar(){ //移除头像的操作
      this.stuForm.headimgurl=""
    },
    //点击确定按钮的操作
    commitStuInfo(formName) {
      this.$refs[formName].validate((valid) => {
        // console.log(valid); //打印的结果是true和false
        if (valid) {
          //表示验证成功，即表单各项都输入了内容
          //发送请求，进行添加，但是我们首先要判断当前是编辑学员信息 还是 添加学员信息
          if (this.dialogTitle === "增加学员信息") {
            // console.log(this.stuForm);
            api.addStuList(this.stuForm).then((res) => {
              // console.log(res);
              if (res.data.state) {
                //表示添加学员信息成功
                this.GET_STU_INFO(); //更新列表
                this.HIDE_DIALOG(); //关闭dialog框
                this.HIDE_LOADING(); //关闭表格加载动画
                this.$message({
                  message: "添加学员信息成功",
                  type: "success",
                });
              } else {
                //添加学员信息失败
                this.$message.error("添加学员信息失败");
              }
            });
          }else{ //表示的是编辑学员信息
          // console.log(123);
            api.updatedStu(this.stuForm)
            .then(res=>{
              // console.log(res);
              // console.log(456);
                this.GET_STU_INFO(); //更新列表
                this.HIDE_DIALOG(); //关闭dialog框
                this.HIDE_LOADING(); //关闭表格加载动画
                this.$message.success('修改成功')
            })
          }
        } else {
          this.$message.error("请将内容填写完整");
        }
      });
    },
    //头像上传成功的方法
    uploadAvatarSuccess(r){
      // console.log(r);
      //把返回来的图片网络地址添加给stuForm 传给服务器保存到数据库
      if(r.state){ //图片上传成功
        this.stuForm.headimgurl=r.headimgurl
        //为了解决图片上传时，对于空头像上传的问题，我们要进行下面的处理‘
        this.headimgList = [{url:r.headimgurl}]
      }else{
        this.$message.error('图片上传失败')
      }
    },
    //关闭dialog,
    dialogClose(){
         // 清空头像回显的数组
      this.headimgList=[]
      //让偷=头像上传的数量变为1
      this.limit = 1
      this.HIDE_DIALOG()
      //清空dialog中的值，因为如果不清空，当我们点击编辑的时候，就会让数据回显，当我们再次点击添加学员信息的时候，dialog中的数据仍然是，编辑中回显的数据
      this.stuForm = this.oldForm
      // 因为oldFrom中存储了stuFrom中的初始值
      
    }
  },
  watch:{
    currentRow(newVal){
      // 检测 currentRow的数据的变化
        // this.currentRow是从vuex中获取的数据
        //数据回显
        this.stuForm = this.currentRow
        // 头像回显
        this.headimgList = [{url:this.currentRow.headimgurl}]
        // 当检测到编辑的时候，将头像上传的数据该为2
        this.limit = 2
    }
  }
};
</script>

<style scoped lang='less'>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border: #409eff;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}
.avatar-uploader {
  text-align: left;
}

/deep/ .el-upload {
    width: 100px !important;
  height: 100px !important;
line-height: 100px;
}
/deep/ .el-upload-list__item-actions{
      width: 100px !important;
  height: 100px !important;
}
/deep/ .el-upload-list__item-thumbnail{
       width: 100px !important;
  height: 100px !important;
}
/deep/ .el-upload-list__item{
       width: 100px !important;
  height: 100px !important;
}
</style>